import 'dart:ffi';
import 'dart:ui';

import 'package:bit_fury/controller/invite_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class UserContractResponse {
  final String? btcNum;
  final String? btcPrice;
  final String?btcInviteNum; 
  final String? url;
  final List<UserContract>? list;
  final int? nowTime;
  final int? noticeNum;
  final double? power;

  UserContractResponse({
    this.btcNum,
    this.btcPrice,
    this.btcInviteNum,
    this.url,
    this.list,
    // this.lineChart,
    this.noticeNum,
    this.nowTime,
    this.power,
  });

  factory UserContractResponse.fromJson(Map<String, dynamic> json) {
    return UserContractResponse(
      btcNum: json['btc_num'],
      btcPrice: json['btc_price'],
      btcInviteNum: json['invite_btc'],
      url: json['url'],
      list: json['list'] != null
          ? (json['list'] as List)
              .map((item) => UserContract.fromJson(item))
              .toList()
          : null,
      // lineChart: json['line_char'] != null
      //     ? LineChart.fromJson(json['line_char'])
      //     : null,
      noticeNum: json['notice_num'],
      nowTime: json['now_time'],
      power: json['power'],
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};

    if (btcNum != null) data['btc_num'] = btcNum;
    if (btcPrice != null) data['btc_price'] = btcPrice;
    if (btcInviteNum != null) data['invite_btc'] = btcInviteNum;
    if (url != null) data['url'] = url;
    if (list != null)
      data['list'] = list!.map((item) => item.toJson()).toList();
    // if (lineChart != null) data['line_char'] = lineChart!.toJson();
    if (nowTime != null) data['now_time'] = nowTime;
    if (noticeNum != null) data['notice_num'] = noticeNum;
    if (power != null) data['power'] = power;
    return data;
  }

  /// 获取BTC数量的数值（安全）
  double get btcNumValue => double.tryParse(btcNum ?? '0') ?? 0.0;

  /// 获取邀请BTC数量的数值（安全）
  double get btcInviteNumValue => double.tryParse(btcInviteNum ?? '0') ?? 0.0;

  /// 获取BTC价格的数值（安全）
  double get btcPriceValue => double.tryParse(btcPrice ?? '0') ?? 0.0;

  /// 计算BTC总价值（USD）
  double get btcTotalValue => btcNumValue * btcPriceValue;

  /// 获取当前时间（安全）
  DateTime? get currentTime => nowTime != null
      ? DateTime.fromMillisecondsSinceEpoch(nowTime! * 1000)
      : null;

  /// 获取合约列表（安全）
  List<UserContract> get contractList => list ?? [];

  /// 获取运行中的合约数量
  int get runningContractsCount =>
      contractList.where((c) => c.status == 1).length;

  /// 获取总算力
  // double get totalComputingPower => contractList.fold(0.0, (sum, contract) => sum + (contract.computingPower ?? 0.0));

  /// 是否有BTC余额信息
  bool get hasBtcInfo => btcNum != null && btcPrice != null;

  /// 是否有图表数据
  // bool get hasChartData => lineChart != null;

  /// 是否有合约列表
  bool get hasContracts => list != null && list!.isNotEmpty;
}

/// 用户合约模型（所有字段可选）
class UserContract {
  final int? id;
  final int? type;
  final String? title;
  final int? status;
  final num? computingPower;
  final String? describe;
  final int? startAt;
  final int? endAt;
  final String? perUsd;
  final int? remaining;
  final String? startTime;
  final String? endTime;

  UserContract({
    this.id,
    this.type,
    this.title,
    this.status,
    this.computingPower,
    this.describe,
    this.startAt,
    this.endAt,
    this.perUsd,
    this.remaining,
    this.startTime,
    this.endTime,
  });

  factory UserContract.fromJson(Map<String, dynamic> json) {
    return UserContract(
      id: json['id'],
      type: json['type'],
      title: json['title'],
      status: json['status'],
      computingPower: json['computing_power'],
      describe: json['describe'],
      startAt: json['start_at'],
      endAt: json['end_at'],
      perUsd: json['per_usd'],
      remaining: json['remaining'],
      startTime: json['start_time'],
      endTime: json['end_time'],
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};

    if (id != null) data['id'] = id;
    if (type != null) data['type'] = type;
    if (title != null) data['title'] = title;
    if (status != null) data['status'] = status;
    if (computingPower != null) data['computing_power'] = computingPower;
    if (describe != null) data['describe'] = describe;
    if (startAt != null) data['start_at'] = startAt;
    if (endAt != null) data['end_at'] = endAt;
    if (perUsd != null) data['per_usd'] = perUsd;
    if (remaining != null) data['remaining'] = remaining;
    if (startTime != null) data['start_time'] = startTime;
    if (endTime != null) data['end_time'] = endTime;

    return data;
  }

  /// 合约类型枚举（安全）
  UserContractType get contractType {
    if (type == null) return UserContractType.unknown;
    switch (type!) {
      case 0:
        return UserContractType.ads;
      case 1:
        return UserContractType.daily;
      case 2:
        return UserContractType.paid;
      default:
        return UserContractType.unknown;
    }
  }

  /// 合约状态（安全）
  bool get isRunning => status == 1;
  bool get isExpired => status == 0;

  /// 获取开始时间（安全）
  DateTime? get startDateTime => startAt != null
      ? DateTime.fromMillisecondsSinceEpoch(startAt! * 1000)
      : null;

  /// 获取结束时间（安全）
  DateTime? get endDateTime =>
      endAt != null ? DateTime.fromMillisecondsSinceEpoch(endAt! * 1000) : null;

  /// 获取每USD收益（安全）
  double get perUsdValue => double.tryParse(perUsd ?? '0') ?? 0.0;

  /// 获取剩余时间（秒）（安全）
  int get remainingSeconds => remaining ?? 0;

  /// 获取剩余时间（小时）
  double get remainingHours => remainingSeconds / 3600.0;

  /// 获取剩余时间（天）
  double get remainingDays => remainingHours / 24.0;

  /// 格式化算力显示（安全）
  // String get formattedComputingPower {
  //   final power = computingPower ?? 0.0;
  //   if (power >= 1000) {
  //     return '${(power / 1000).toStringAsFixed(1)} Th/s';
  //   } else {
  //     return '${power.toStringAsFixed(1)} Gh/s';
  //   }
  // }

  /// 获取标题（安全）
  String get safeTitle => title ?? '--';

  /// 获取描述（安全）
  String get safeDescribe => describe ?? '--';

  /// 是否有时间信息
  bool get hasTimeInfo => startAt != null && endAt != null;

  /// 是否有收益信息
  bool get hasRevenueInfo => perUsd != null;

  /// 是否有完整信息
  bool get hasCompleteInfo => id != null && title != null && status != null;

  String get remainingTimeText {
    if (remaining == null || remaining! <= 0) {
      return '0';
    }

      final remainingSeconds = endAt! - startAt!;
      final duration = Duration(seconds: remainingSeconds);
      final hours = duration.inHours;
      final minutes = duration.inMinutes.remainder(60);

      return 'Remaining ${hours}h ${minutes}m';
  }

  Color getStatusColor(int status) {
    switch (status) {
      case 1:
        return Colors.green;
      case 0:
        return Colors.red;

      default:
        return Colors.orange;
    }
  }

  String getStatusText(int status) {
    switch (status) {
      case 1:
        return 'running'.tr;
      case 0:
        return 'stopped'.tr;

      default:
        return 'unknown'.tr;
    }
  }

  String getTypeText(int status) {
    switch (status) {
      case 1:
        return 'invite_contract'.tr;
      case 0:
        return 'ad_contract'.tr;

      case 2:
        return 'checkin_contract'.tr;
      case 3:
        return 'subscription_contract'.tr;

      default:
        return 'unknown_contract'.tr;
    }
  }
}

/// 算力图表数据模型（所有字段可选）
class LineChart {
  final String? min;
  final String? max;
  final List<double>? list;

  LineChart({
    this.min,
    this.max,
    this.list,
  });

  factory LineChart.fromJson(Map<String, dynamic> json) {
    return LineChart(
      min: json['min'],
      max: json['max'],
      list: json['list'] != null
          ? (json['list'] as List)
              .map((item) => (item as num).toDouble())
              .toList()
          : null,
    );
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = {};

    if (min != null) data['min'] = min;
    if (max != null) data['max'] = max;
    if (list != null) data['list'] = list;

    return data;
  }

  /// 获取数据列表（安全）
  List<double> get dataList => list ?? [];

  /// 获取最小值
  double get minValue =>
      dataList.isNotEmpty ? dataList.reduce((a, b) => a < b ? a : b) : 0.0;

  /// 获取最大值
  double get maxValue =>
      dataList.isNotEmpty ? dataList.reduce((a, b) => a > b ? a : b) : 0.0;

  /// 获取平均值
  double get averageValue => dataList.isNotEmpty
      ? dataList.reduce((a, b) => a + b) / dataList.length
      : 0.0;

  /// 是否有有效数据
  bool get hasValidData => list != null && list!.isNotEmpty;

  /// 获取最小值标签（安全）
  String get minLabel => min ?? '--';

  /// 获取最大值标签（安全）
  String get maxLabel => max ?? '--';
}

/// 用户合约类型枚举
enum UserContractType {
  ads, // 广告合约
  daily, // 每日签到
  paid, // 付费合约
  unknown // 未知类型
}
